<?php
class Rating extends AppModel {

	var $name = 'Rating';
	var $useTable = 'ratings';

	function getRatings($type, $item_id, $user_id=null)
	{
		if(!is_null($user_id))
		{
			// find average of scores
			$scores = $this->query('SELECT avg( rating ) as rating FROM `ratings` WHERE item_id ='.$item_id.' and type ="'.$type.'" and user_id='.$user_id);
		}
		else
		{
			// find average of scores
			$scores = $this->query('SELECT avg( rating ) as rating FROM `ratings` WHERE item_id ='.$item_id.' and type ="'.$type.'"');
		}
		return $scores[0][0]['rating'];
	}

	function getTopRated($type, $number)
	{
		if($number)
			$topRated = $this->query('SELECT item_id, avg( rating ) as rating FROM `ratings` where type ="'.$type.'" group by item_id order by rating desc limit '.$number);
		else
			$topRated = $this->query('SELECT item_id, avg( rating ) as rating FROM `ratings` where type ="'.$type.'" group by item_id order by rating desc');

		return Set::extract($topRated, '{n}.ratings.item_id');
	}

	function getAvgRating($ids=null, $type)
	{
		
		if(is_array($ids))
		{
			$score = $this->query('SELECT avg( rating ) as rating FROM `ratings` WHERE item_id IN ('.implode($ids, ',').') and type ="'.$type.'"');
		}
		else
		{
			$score = $this->query('SELECT avg( rating ) as rating FROM `ratings` WHERE item_id ='.$ids.' and type ="'.$type.'"');
		}
		return round($score[0][0]['rating'], 2);
	}
}
?>